package cn.leedsoft.luma.plugins.shiro;

import cn.leedsoft.luma.mapper.domain.User;
import cn.leedsoft.luma.mapper.domain.UserExample;
import cn.leedsoft.luma.mapper.generate.UserMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by leeds on 2016/7/7 22:24.
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    /**
     * 获取角色和授权等信息
     * 使用：基于角色的访问控制
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User u = (User) principals.getPrimaryPrincipal();
        if (u == null || u.getRoleId() == null) {
            return authorizationInfo;
        }
        authorizationInfo.addRole(u.getRoleId().toString());
//            List<Resource> resList = roleMem.getResourcesByRoleId(u.getRoleId());
//            if (resList != null) {
//                for (Resource res : resList) {
//                    authorizationInfo.addStringPermission(res.getPermission());
//                }
//            }
        return authorizationInfo;
    }

    /**
     * 验证登陆
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String cellphone = (String) token.getPrincipal();
        UserExample userExample = new UserExample();
        userExample.createCriteria().andCellphoneEqualTo(cellphone);
        List<User> users = userMapper.selectByExample(userExample);
        if (users.size() == 0) {
            throw new UnknownAccountException();// 没找到帐号
        }
        User user = users.get(0);
        if (user.getState().intValue() != 0) {
            throw new LockedAccountException(); // 帐号锁定
        }

        // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, // 用户名
                user.getPassword(), // 加密后的密码
                ByteSource.Util.bytes(user.getSalt()),// salt
                getName() // realm name
        );
        return authenticationInfo;
    }

}
